﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO.Ports;

namespace PreMixZone
{
    public partial class PreMix : Form
    {
        private String strConn = "Data Source=163.50.57.11\\sqlt;Initial Catalog=MT300_Mixing;Integrated Security=True";
        private Function f = new Function();
        private delegate void SetTextCallback(string text);

        private String InputData_SN5468 = String.Empty;
        private String InputData_ASF189_GI22_ZAABLY903 = String.Empty;

        private String txt_SN5468 = String.Empty;
        private String txt_ASF189_GI22_ZAABLY903 = String.Empty;

        private int Weigth_Count = 0;

        public PreMix()
        {
            InitializeComponent();
        }

        private void cb_ID_SelectedIndexChanged(object sender, EventArgs e)
        {
            tb_LotID.Focus();
            lb_Status.Text = cb_ID.Text;
        }

        private void tb_LotID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_LotID.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter && cb_ID.Text == "")
            {
                tb_LotID.Text = "";
                lb_Status.Text = "เลือกรหัสพนักงาน";
            }
            else if (e.KeyCode == Keys.Enter)
            {
                tb_SLMPart.Focus();
            }
        }

        private void tb_SLMPart_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_SLMPart.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter && tb_LotID.Text == "")
            {
                tb_SLMPart.Text = "";
                lb_Status.Text = "สแกนล็อต";
            }
            else if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        connection.Open();
                        using (SqlCommand command = connection.CreateCommand())
                        {
                            command.CommandText = "SELECT * From SLM_Part WHERE  SLMPart like'%" + f.findSLMPart(tb_SLMPart.Text) + "%'";

                            SqlDataReader reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                lb_sn.Text = reader["SN5468"].ToString().Split('@')[0];
                                lb_sn_error.Text = reader["SN5468"].ToString().Split('@')[1];

                                

                                lb_asf_gi.Text = reader["ASF1891#GI22#ZAABL903"].ToString().Split('#')[0];
                                lb_asfgi.Text = reader["ASF1891#GI22#ZAABL903"].ToString().Split('#')[1].Split('@')[0];
                                lb_asfgi_error.Text = reader["ASF1891#GI22#ZAABL903"].ToString().Split('#')[1].Split('@')[1];

                                if (lb_asf_gi.Text == "XXX")
                                {
                                    asfgiHide();
                                }
                                else {
                                    asfgiShow();
                                }

                                AutoConfig();
                            }//while
                        }
                    }
                }
                catch
                {
                    lb_Status.Text = "ไม่พบข้อมูล";
                }
            }
        }

        private void PreMix_Load(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT * From Emp_ID WHERE Position = 'mix'";

                        SqlDataReader reader = command.ExecuteReader();
                        SqlDataReader tmp = reader;

                        while (reader.Read())
                        {
                            cb_ID.Items.Add(reader["Emp_ID"]);
                        }
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Network Failed";
            }

            comPort();
            //AutoConfig();
        }

        public void comPort()
        {
            string[] ports = SerialPort.GetPortNames();

            foreach (string port in ports)
            {
                cb_rs232_sn.Items.Add(port);
                cb_rs232_asfgi.Items.Add(port);
                cb_rs232_sn_18.Items.Add(port);
            }
        }

        public void AutoConfig()
        {
            try
            {

                serialPort_sn.Close();
                serialPort_asfgi.Close();
                serialPort_sn_18.Close();
            }
            catch
            {
                //
            }

            try
            {
                string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\PreMixZone.txt");
                cb_rs232_sn.SelectedIndex = cb_rs232_sn.FindString(lines[0].ToString());
                cb_rs232_asfgi.SelectedIndex = cb_rs232_asfgi.FindString(lines[1].ToString());
                cb_rs232_sn_18.SelectedIndex = cb_rs232_sn_18.FindString(lines[1].ToString());

            }
            catch
            {
                serialPort_sn.Close();
                serialPort_sn_18.Close();
                serialPort_asfgi.Close();
            }
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            cb_rs232_sn.Enabled = true;
            cb_rs232_sn.Items.Remove(serialPort_sn.PortName);

            cb_rs232_asfgi.Enabled = true;
            cb_rs232_asfgi.Items.Remove(serialPort_asfgi.PortName);


            comPort();
        }

        private void tb_sn_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double sn = Double.Parse("0" + lb_sn.Text);
                double Error_1 = Double.Parse("0" + lb_sn_error.Text);
                double com = Double.Parse("0" + tb_sn.Text);
                if (com >= (sn - Error_1) && (com <= sn + Error_1))
                {
                    lb_sn_just.Text = "G";
                    lb_sn_just.BackColor = Color.Green;
                    lb_sn_just.ForeColor = Color.White;
                }
                else
                {
                    lb_sn_just.Text = "NG";
                    lb_sn_just.BackColor = Color.Red;
                    lb_sn_just.ForeColor = Color.White;
                }
            }
            catch
            {
                //
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Premix (LotNumber, SLMPart,Emp_ID, SN5468, SN5468_Status, Datetimes) VALUES (@LotNumber, @SLMPart,@Emp_ID, @SN5468, @SN5468_Status, @Datetimes)";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());
                        command.Parameters.AddWithValue("@SN5468", tb_sn.Text);
                        command.Parameters.AddWithValue("@SN5468_Status", lb_sn_just.Text);                        
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }
        }

        private void tb_asfgi_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double asfgi = Double.Parse("0" + lb_asfgi.Text);
                double Error_1 = Double.Parse("0" + lb_asfgi_error.Text);
                double com = Double.Parse("0" + tb_asfgi.Text);
                if (com >= (asfgi - Error_1) && (com <= asfgi + Error_1))
                {
                    lb_asfgi_just.Text = "G";
                    lb_asfgi_just.BackColor = Color.Green;
                    lb_asfgi_just.ForeColor = Color.White;
                }
                else
                {
                    lb_asfgi_just.Text = "NG";
                    lb_asfgi_just.BackColor = Color.Red;
                    lb_asfgi_just.ForeColor = Color.White;
                }
            }
            catch
            {
                //
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Premix (LotNumber, SLMPart,Emp_ID, SN5468, SN5468_Status, Datetimes, ASFGI_Type, ASFGI, ASFGI_Status) VALUES (@LotNumber, @SLMPart,@Emp_ID, @SN5468, @SN5468_Status, @Datetimes, @ASFGI_Type, @ASFGI, @ASFGI_Status)";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());

                        command.Parameters.AddWithValue("@SN5468", tb_sn.Text);
                        command.Parameters.AddWithValue("@SN5468_Status", lb_sn_just.Text);

                        command.Parameters.AddWithValue("@ASFGI_Type", lb_asf_gi.Text);
                        command.Parameters.AddWithValue("@ASFGI", tb_asfgi.Text);
                        command.Parameters.AddWithValue("@ASFGI_Status", lb_asfgi_just.Text);


                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Premix (LotNumber, SLMPart,Emp_ID, SN5468, SN5468_Status, Datetimes, ASFGI_Type, ASFGI, ASFGI_Status) VALUES (@LotNumber, @SLMPart,@Emp_ID, @SN5468, @SN5468_Status, @Datetimes, @ASFGI_Type, @ASFGI, @ASFGI_Status)";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());

                        command.Parameters.AddWithValue("@SN5468", tb_sn.Text);
                        command.Parameters.AddWithValue("@SN5468_Status", lb_sn_just.Text);

                        command.Parameters.AddWithValue("@ASFGI_Type", lb_asf_gi.Text);
                        command.Parameters.AddWithValue("@ASFGI", tb_asfgi.Text);
                        command.Parameters.AddWithValue("@ASFGI_Status", lb_asfgi_just.Text);


                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }

            this.Controls.Clear();
            this.InitializeComponent();
            comPort();
            //AutoConfig();


        }

        private void tb_LotSreach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_SLMPart.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                lsv_Reports.Clear();

                lsv_Reports.Columns.Add("เลขล๊อต", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("รุ่นงาน", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("SN5468", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("สถานะ", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("ASFGI", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("น้ำหนัก", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("สถานะ", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("พนักงาน", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("ว/ด/ป", 200, HorizontalAlignment.Center);

                lsv_Reports.View = View.Details;
                lsv_Reports.GridLines = true;
                lsv_Reports.FullRowSelect = true;

                try
                {
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        connection.Open();
                        using (SqlCommand command = connection.CreateCommand())
                        {
                            command.CommandText = "SELECT TOP 1 * From History_Premix WHERE LotNumber ='" + tb_LotSreach.Text + "' AND( SN5468_Status ='G' OR ASFGI_Status='G') ORDER BY Datetimes DESC";

                            SqlDataReader reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                ListViewItem listitem = new ListViewItem(reader["LotNumber"].ToString());
                                listitem.SubItems.Add(reader["SLMPart"].ToString());

                                listitem.SubItems.Add(reader["SN5468"].ToString());
                                listitem.SubItems.Add(reader["SN5468_Status"].ToString());

                                listitem.SubItems.Add(reader["ASFGI_Type"].ToString());
                                listitem.SubItems.Add(reader["ASFGI"].ToString());
                                listitem.SubItems.Add(reader["ASFGI_Status"].ToString());

                                
                                listitem.SubItems.Add(reader["Emp_ID"].ToString());
                                listitem.SubItems.Add(reader["Datetimes"].ToString());

                                lsv_Reports.Items.Add(listitem);
                            }
                        }
                    }
                }
                catch
                {
                    lb_Status.Text = "Network Failed";
                }
            }
        }


        ///////////////////////////////////////////////////////////////////////////////////////

        private void cb_rs232_sn_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SN5468_config(cb_rs232_sn.SelectedItem.ToString());
                cb_rs232_sn.Enabled = false;
            }
            catch
            {
                //
            }
        }


        private void serialPort_sn_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                InputData_SN5468 = serialPort_sn.ReadLine();
                if (InputData_SN5468 != String.Empty)
                {
                    SetText_SN5468(InputData_SN5468);
                }
            }
            catch
            {
                //
            }
        }

        

        public void SN5468_config(String txt)
        {
            if (serialPort_sn.IsOpen)
                serialPort_sn.Close();
            serialPort_sn.PortName = txt;
            serialPort_sn.BaudRate = 9600;
            serialPort_sn.StopBits = StopBits.One;
            serialPort_sn.Parity = Parity.None;
            serialPort_sn.DataBits = 8;

            //cb_rs232_sn.Text = txt;

            //comboBox_SN5468.Items.Remove(serialPort_sn.PortName);
            

            if (f.SearchString(tb_SLMPart.Text, "18"))
            {
                cb_rs232_asfgi.Items.Remove(serialPort_sn.PortName);
                cb_rs232_sn.Items.Remove(serialPort_sn.PortName);
                cb_rs232_sn_18.Enabled = false;
            }
            else {
                cb_rs232_asfgi.Items.Remove(serialPort_sn.PortName);
                cb_rs232_sn_18.Items.Remove(serialPort_sn.PortName);
                cb_rs232_sn.Enabled = false;
            }
            

            try
            {
                serialPort_sn.Open();
            }
            catch
            {
                //
                serialPort_sn.Close();
            }
        }

        private void SetText_SN5468(string text)
        {
            if (this.tb_sn.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText_SN5468);

                this.Invoke(d, new object[] { text });
            }
            else if (Weigth_Count == 1)
            {
                tb_sn.Text = text.Replace(" ", String.Empty).Replace("GS", String.Empty).Replace("NT", String.Empty).Replace("g", String.Empty).Replace("TOTAL:", String.Empty);
                Weigth_Count++;
            }
            else
            {
                Weigth_Count++;
            }

            if (Weigth_Count == 4)
            {
                Weigth_Count = 0;
            }
        }


        ///////////////////////////////////////////////////////////////////////////////////////

        private void cb_rs232_sn_18_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SN5468_config(cb_rs232_sn_18.SelectedItem.ToString());
                cb_rs232_sn_18.Enabled = false;
            }
            catch
            {
                //
            }
        }


        private void serialPort_sn_18_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                InputData_SN5468 = serialPort_sn_18.ReadLine();
                if (InputData_SN5468 != String.Empty)
                {
                    if (InputData_SN5468.Substring(0, 3) == "Net") {
                        SetText_SN5468(InputData_SN5468);
                    }
                    
                }
            }
            catch
            {
                //
            }
        }

        private void SetText_SN5468_18(string text)
        {
            if (this.tb_sn.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText_SN5468_18);

                this.Invoke(d, new object[] { text });
            }
            else if (Weigth_Count == 1)
            {
                tb_sn.Text = text.Replace(" ", String.Empty).Replace("KG", String.Empty).Replace("g", String.Empty);
                Weigth_Count++;
            }
            else
            {
                Weigth_Count++;
            }

            if (Weigth_Count == 4)
            {
                Weigth_Count = 0;
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////

        private void cb_rs232_asfgi_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ASF189_GI22_ZAABLY903_config(cb_rs232_asfgi.SelectedItem.ToString());
                cb_rs232_asfgi.Enabled = false;
            }
            catch
            {
                //
            }
        }


        private void serialPort_asfgi_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                InputData_ASF189_GI22_ZAABLY903 = serialPort_asfgi.ReadLine();
                if (InputData_ASF189_GI22_ZAABLY903 != String.Empty)
                {
                    SetText_ASF189_GI22(InputData_ASF189_GI22_ZAABLY903);
                }
            }
            catch
            {
                //
            }
        }


        public void ASF189_GI22_ZAABLY903_config(String txt)
        {
            if (serialPort_asfgi.IsOpen)
                serialPort_asfgi.Close();
            serialPort_asfgi.PortName = txt;
            serialPort_asfgi.BaudRate = 9600;
            serialPort_asfgi.StopBits = StopBits.One;
            serialPort_asfgi.Parity = Parity.None;
            serialPort_asfgi.DataBits = 8;

            cb_rs232_asfgi.Text = txt;

            cb_rs232_sn.Items.Remove(serialPort_asfgi.PortName);
            cb_rs232_sn_18.Items.Remove(serialPort_asfgi.PortName);
            //comboBox_Main_ASF189_GI22_ZAABLY903.Items.Remove(serialPort_asfgi.PortName);
            cb_rs232_asfgi.Enabled = false;
            try
            {
                serialPort_asfgi.Open();
            }
            catch
            {
                //
                serialPort_asfgi.Close();
            }
        }

        

        private void SetText_ASF189_GI22(string text)
        {
            if (this.tb_asfgi.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText_ASF189_GI22);

                this.Invoke(d, new object[] { text });
            }
            else if (Weigth_Count == 1)
            {
                txt_ASF189_GI22_ZAABLY903 = text;
                tb_asfgi.Text = text.Replace(" ", String.Empty).Replace("GS", String.Empty).Replace("NT", String.Empty).Replace("g", String.Empty).Replace("TOTAL:", String.Empty);
                Weigth_Count++;
            }
            else
            {
                Weigth_Count++;
            }

            if (Weigth_Count == 4)
            {
                Weigth_Count = 0;
            }
        }


        ///////////////////////////////////////////////////////////////////////////////////////


        public void asfgiHide() { 
            lb_asfgi_just.Hide();
            lb_asf_gi.Hide();
            tb_asfgi.Hide();
            lb_asfgi.Hide();
            lb_asfgi_error.Hide();
        }

        public void asfgiShow()
        {
            lb_asfgi_just.Show();
            lb_asf_gi.Show();
            tb_asfgi.Show();
            lb_asfgi.Show();
            lb_asfgi_error.Show();
        }

       

        

        

        
    }
}
